const treeUtils = {
    listToTree: function (list, mk = "id", pk = "parentId", childrenKey = "children") {

        if (!list || list.length < 1) return list;
        let rootNodes = treeUtils.findAllRoots(list, mk, pk)
        if (!rootNodes || rootNodes.length < 1) return list;
        for (let i = 0; i < rootNodes.length; i++) {
            let item = rootNodes[i];
            let childNodes = treeUtils.findChildren(list, item[mk], mk, pk, childrenKey)
            if (!childNodes || childNodes.length < 1) continue
            if (!item[childrenKey]) item[childrenKey] = []
            item[childrenKey] = item[childrenKey].concat(childNodes)
        }

        return rootNodes
    },
    findAllRoots: function (list, mk, pk) {
        let nodePk = {};
        let rootNodes = [];
        for (let i = 0; i < list.length; i++) {
            let item = list[i];
            if (!item[mk]) continue
            if (nodePk[item[mk]]) continue;
            nodePk[item[mk]] = item;
        }
        // let removeIndexs=[];
        for (let i = 0; i < list.length; i++) {
            let item = list[i];
            if (nodePk[item[pk]]) continue;
            rootNodes.push(item)
            // removeIndexs.push(i)

        }
        // for (let i = 0; i < removeIndexs.length; i++) {
        //     list.splice(removeIndexs[i], 1);
        // }
        return rootNodes;
    },
    findChildren(list, nodeMkValue, mk, pk, childrenKey) {
        let nodes = [];
        if (!list || list.length < 1) return nodes;
        for (let i = 0; i < list.length; i++) {
            let item = list[i];
            if (item[pk] !== nodeMkValue) continue
            nodes.push(item)
            // list.splice(i, 1);
            let childNodes = treeUtils.findChildren(list, item[mk], mk, pk, childrenKey)
            if (!childNodes || childNodes.length < 1) continue
            if (!item[childrenKey]) item[childrenKey] = []
            item[childrenKey] = item[childrenKey].concat(childNodes)
        }
        return nodes;
    }
}

export default treeUtils
